package com.hunzi.controller;

import com.hunzi.domain.User;
import com.hunzi.service.UserService;
import com.ramostear.captcha.HappyCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService ;


    //1.实现用户登录的功能 传入 用户输入的用户名 密码 和 验证码
    @RequestMapping("/login")
    public String login(String username , String password , String captcha , HttpServletRequest request , Model model){
        //1.当用户登录的时候进行验证码的验证
        /** HttpServletRequest request 请求对象
         *String code 用户输入的验证码
         * Boolean ignoceCase 是否忽略大小写 true为忽略大小写
         * 方法返回为boolean类型 true表示验证通过 ， false表示验证失败
         */
        boolean verification = HappyCaptcha.verification ( request, captcha, true );
        //1.2.如果验证失败，回显登录页面，提示用户再次登录
        if (!verification){
              model.addAttribute ( "error" , "验证码输入错误" );
              //回显到登录页面
              return "login";
        }
        //2.调用登录功能
    //2.1从数据库中查询用户对象
    User user = userService.loginUser ( username, password );
    //2.2判断用户对象是否为空
        if (user != null){
        //1.如果用户登录成功，将用户对象放入session域中，用来跟踪用户登录状态
        //使用request对象获取session对象
        request.getSession ().setAttribute ( "user" , user );
        //2.登录成功重定向到首页
        return "redirect:/";
    }else{
        model.addAttribute ( "error" ,"用户名或密码错误" );
        //回显到登录页面
        return "login";
    }

}

    //2.用户退出
    @RequestMapping("/out")
    public String loginOutUser(HttpSession session ){
        //删除user的session值
        session.removeAttribute ( "user" );
        //返回首页
        return "redirect:/" ;
    }

    //3.用户注册
    @RequestMapping("/registerUesr")
    public  String registerUesr(User user , Model model ){
        int insert = userService.insert ( user );
        model.addAttribute ( "error" , "用户注册成功,请登录！" );
        return "login";
    }


}
